//路由鉴权
import router from "@/router";
import progress from 'nprogress';
import "nprogress/nprogress.css";
import useUserStore from "@/store/modules/user.ts";
import pinia from './store';


progress.configure({ showSpinner: false})

let userStore = useUserStore(pinia);

//全局前置守卫
router.beforeEach(async (to: any, from: any, next: any) => {
    //to:你要访问那个路由
    //from:你从那个路由而来
    //next:放行方法
    progress.start();

    let token = userStore.token;
    let username = userStore.username;
    if (token){
        if (to.path =='/login'){
            next({path:'/'});
        }else {
            if (username){
                next();
            }else {
              try {
                  //获取用户信息在方向
                  await userStore.userInfo();
                  next();
              }catch (error){
                await userStore.logout();
                next({path:'/login'});
              }
            }
        }

    }else {
        if (to.path =='/login'){
            next();
        }else{
            next({path:'/login'});
        }
    }
    next();
})

//全局后置守卫
router.afterEach((to: any, from: any, next: any) => {
    progress.done();
})


